<!--
  *  员工 表单 弹窗
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-08-08 20:46:18
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
    <a-drawer
            title="新增医生临时排班【仅用临时排班约束】"
            :width="600"
            :visible="visible"
            :body-style="{ paddingBottom: '80px' }"
            @close="onClose"
            destroyOnClose
    >

        <p class="hint" style="color:red;">如果有大的排班的调整修改的话，需重新定制排班系统规则！或修改排班规则！</p>
        <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">

            <a-form-item label="医生头像" name="icon">
                <a-image :src="form.icon" disabled style="max-width: 150px; max-height: 150px;"/>
            </a-form-item>
            <a-form-item label="医生名称" name="name">
                <a-input v-model:value.trim="form.name" disabled placeholder="请输入医生名称"/>
            </a-form-item>

            <a-form-item label="驻点医馆" name="si_number">
                <a-select v-model:value="form.si_number" optionFilterProp="title"
                          placeholder="请选择医生驻点医馆">
                    <a-select-option v-for="item in doctorStationNameList" :key="item.valueCode"
                                     :value="item.valueCode" :title="item.valueName">{{ item.valueName }}
                    </a-select-option>
                </a-select>

            </a-form-item>

            <a-form-item label="排班日期" name="scheduling_dnotime" >
                <a-space direction="vertical" :size="12">
                    <a-date-picker  value-format="YYYY-MM-DD" format="YYYY-MM-DD" v-model:value="form.scheduling_dnotime"
                                    style="width: 550px" @change="onChangeCreateTime"/>
                </a-space>
            </a-form-item>

            <a-form-item label="排班时段" name="scheduling_ampm">
                <a-select v-model:value="form.scheduling_ampm" optionFilterProp="title"
                          placeholder="请选择排班时段" @change="findItemNameAmPm">
                    <a-select-option value="am">上午</a-select-option>
                    <a-select-option value="pm">下午</a-select-option>
                </a-select>
            </a-form-item>

            <a-form-item v-if="select_ampm=='am'" label="早上排班起始时间" name="interval_am_sart" >
                <p class="hint">表示早上开始排班的起始时间</p>
                <a-input v-model:value.trim="form.interval_am_sart" placeholder="请输入医生早上排班起始时间"/>
            </a-form-item>
            <a-form-item v-if="select_ampm=='am'" label="早上排班截止时间" name="interval_am_end">
                <p class="hint">表示早上开始排班的截止时间</p>
                <a-input v-model:value.trim="form.interval_am_end" placeholder="请输入医生早上排班起始时间"/>
            </a-form-item>
            <a-form-item v-if="select_ampm=='pm'"  label="下午排班起始时间" name="interval_pm_sart">
                <p class="hint">表示下午开始排班的起始时间</p>
                <a-input v-model:value.trim="form.interval_pm_sart" placeholder="请输入医生下午排班起始时间"/>
            </a-form-item>
            <a-form-item v-if="select_ampm=='pm'" label="下午排班截止时间" name="interval_pm_end">
                <p class="hint">表示下午开始排班的截止时间</p>
                <a-input v-model:value.trim="form.interval_pm_end" placeholder="请输入医生下午排班起始时间"/>
            </a-form-item>



            <a-form-item label="间隔时段(单位/分钟)" name="interval_time">
                <p class="hint">表示每隔多少分钟排一次班</p>
                <a-input v-model:value.trim="form.interval_time" placeholder="请输入医生间隔时段"/>
            </a-form-item>

            <a-form-item label="时段号源数" name="interval_scheduling_stock">
                <p class="hint">表示每个时段放出的号源数量</p>
                <a-input v-model:value.trim="form.interval_scheduling_stock" placeholder="请输入显示时段号源数"/>
            </a-form-item>




        </a-form>
        <div class="footer">
            <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
            <a-button type="primary" style="margin-right: 8px" @click="onSubmit(false)">
                确定新增临时排班
            </a-button>
        </div>
    </a-drawer>
</template>
<script setup lang="ts">
import {message} from 'ant-design-vue';
import _ from 'lodash';
import {nextTick, reactive, ref} from 'vue';
import {roleApi} from '/@/api/system/role/role-api';
import {businessesApi} from '/@/api/system/infirmary/businesses-api';
import DepartmentTreeSelect from '/@/components/system/department-tree-select/index.vue';
import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
import {GENDER_ENUM} from '/@/constants/common-const';
import {regular} from '/@/constants/regular-const';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {smartSentry} from '/@/lib/smart-sentry';
import {defaultTimeRanges} from "/@/lib/default-time-ranges";
import moment from 'moment';

// ----------------------- 以下是字段定义 emits props ---------------------
const departmentTreeSelect = ref();
// emit
const emit = defineEmits(['refresh', 'show-account']);

const Appid = ref(undefined);

// 医生实体记录
const DoctorRecord = ref(undefined);

const DoctorRecordNameTitle = ref(undefined);
const DoctorRecordName = ref(undefined);
const doctorInterimSchedulingFormModal = ref();

// ----------------------- 显示/隐藏 ---------------------

const visible = ref(false); // 是否展示抽屉
const iselecectAmpm = ref(false); // 是否展示抽屉

// 选择的是上午还是下午
const select_ampm = ref(undefined);

// 隐藏
function onClose() {
    reset();
    visible.value = false;
    iselecectAmpm.value = false;
    formDefault.scheduling_dnotime = undefined
    select_ampm.value= undefined
}

// 显示
async function showDrawer(record, appid) {
    // console.log("关闭了as显示",rowData,!_.isEmpty(rowData))
    //是否是修改或新增
    // 刚打开的时候默认是不显示，只有选择了上午或下午的时候才会去显示
    iselecectAmpm.value = false;

    Appid.value = appid;
    DoctorRecord.value = record;
    visible.value = true;
    DoctorRecordName.value = record.name
    // 默认初始化新的值信息
    formDefault.appid = appid;
    formDefault.icon = record.icon;
    formDefault.name = record.name;
    formDefault.dc_number = record.dc_number;

    Object.assign(form, formDefault);
    visible.value = true;

    nextTick(() => {
        // 执行异步获取医馆列表信息
        // 获取当前医馆的驻点的分医馆的列表
        queryAllDoctorStationNameList(Appid.value);
    });

}

// ----------------------- 表单显示 ---------------------
const doctorStationNameList = ref([]); //当前医馆驻点医馆列表
async function queryAllDoctorStationNameList(appid) {
    // 只查询当前要查询的APPID的医馆信息
    let res = await businessesApi.queryDoctorStationNameListValueList({
        'appid': appid
    });
    doctorStationNameList.value = res.data;
}

// ----------------------- 表单显示 ---------------------


// ----------------------- 表单显示 ---------------------
const formRef = ref(); // 组件ref
// 添加的时候相关表单信息的是否显示的关键点----------清除关键点
const formDefault = {
    id: undefined,
    appid: undefined,
    name: undefined,
    si_name: undefined,
    icon: undefined,
    worktab: undefined,
    si_number: undefined,
    dc_number: undefined,
    workcycle: undefined,
    interval_am_sart: undefined,
    interval_am_end: undefined,
    interval_pm_sart: undefined,
    interval_pm_end: undefined,
    interval_scheduling_stock: undefined,
    interval_days: undefined,
    status: undefined,
    scheduling_ampm: undefined,
    scheduling_dnotime:undefined,
    interval_time: undefined,
};

let form = reactive(_.cloneDeep(formDefault));

function reset() {
    Object.assign(form, formDefault);
    formRef.value.resetFields();
}

// ----------------------- 表单提交 ---------------------
// 表单规则
const rules = {
    si_number: [
        {required: true, message: '医生坐诊驻地医馆不能为空'},
    ],
    scheduling_dnotime : [
        {required: true, message: '坐诊方式不能为空'},
    ],
    ampm: [
        {required: true, message: '坐诊方式不能为空'},
    ],
    worktab: [
        {required: true, message: '坐诊方式不能为空'},
    ],
    workcycle: [
        {required: true, message: '坐诊周期不能为空'},
    ],
    interval_scheduling_stock: [
        {required: true, message: '时段号源总数不能为空'},
    ],
    interval_days: [
        {required: true, message: '显示排班天数不能为空'},
    ],
    interval_time: [
        {required: true, message: '间隔时段不能为空'},
    ],
    interval_am_sart: [
        {required: select_ampm.value==='am'?true:false, message: '早上排班起始时间不能为空'},
    ],
    interval_am_end: [
        {required: select_ampm.value==='am'?true:false, message: '早上排班截止时间不能为空'},
    ],
    interval_pm_sart: [
        {required: select_ampm.value==='pm'?true:false, message: '下午排班起始时间不能为空'},
    ],
    interval_pm_end: [
        {required: select_ampm.value==='pm'?true:false, message: '下午排班截止时间不能为空'},
    ],
    name: [
        {required: true, message: '医馆名称不能为空'},
    ],
    tel: [
        {required: true, message: '联系号码不能为空'},
        {pattern: regular.tel, message: '请输入正确的手机号码', trigger: 'blur'},
    ],
    status: [{required: true, message: '状态不能为空'}],
};

// 校验表单
function validateForm(formRef) {
    return new Promise((resolve) => {
        formRef
            .validate()
            .then(() => {
                resolve(true);
            })
            .catch(() => {
                resolve(false);
            });
    });
}



function findItemNameAmPm(value) {
    console.log('Selected Time: ', value)
    iselecectAmpm.value = true
    select_ampm.value = value
    rules.interval_am_sart[0].required = select_ampm.value==='am'?true:false
    rules.interval_am_end[0].required = select_ampm.value==='am'?true:false
    // 修改规则
    rules.interval_pm_sart[0].required = select_ampm.value==='pm'?true:false
    rules.interval_pm_end[0].required = select_ampm.value==='pm'?true:false

    console.log(rules.interval_am_sart[0].required)
    console.log(rules.interval_am_end[0].required)
    console.log(rules.interval_pm_sart[0].required)
    console.log(rules.interval_pm_end[0].required)
}

function onChangeCreateTime(value, dateString) {
    // queryForm.stime = dateStrings[0];
    // queryForm.etime = dateStrings[1];
    console.log('Selected Time: ', value)
    console.log('Formatted Selected Time: ', dateString)
    formDefault.scheduling_dnotime = dateString
    console.log('Formatted Selected Time: ', formDefault.scheduling_dnotime)
}


// 提交数据
async function onSubmit(keepAdding) {
    let validateFormRes = await validateForm(formRef.value);
    // formRef.value.scheduling_dnotime=new Date(formRef.value.scheduling_dnotime)

    if (!validateFormRes) {
        message.error('参数验证错误，请仔细填写表单数据!');
        return;
    }


    SmartLoading.show();
    // 新增临时排班
    await addNewBusinessesDoctorInterimScheduling()
}

async function addNewBusinessesDoctorInterimScheduling() {
    try {
        console.log('Formatted Selected Timformformforme: ', form)
        let result = await businessesApi.addNewBusinessesDoctorInterimScheduling(form);
        const ok = result.ok;
        message.success(result.msg);
        onClose();
        // emit('refresh');
        emit('reloadList');
    } catch (error) {
        // smartSentry.captureError(error);
    } finally {
        SmartLoading.hide();
    }
}

async function updateBusinessesDoctorStationRule(keepAdding) {
    try {
        let result = await businessesApi.updateBusinessesDoctorStationRule(form);
        const ok = result.ok;
        message.success(result.msg);
        if (keepAdding) {
            reset();
        } else {
            onClose();
        }
        // emit('refresh');
        emit('reloadList');
    } catch (error) {
        // smartSentry.captureError(error);
    } finally {
        SmartLoading.hide();
    }
}

// ----------------------- 以下是暴露的方法内容 ----------------------------
defineExpose({
    showDrawer,
});
</script>
<style scoped lang="less">
.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}

.hint {
  margin-top: 5px;
  color: #bfbfbf;
}
</style>
